
from PySide6.QtCore import QFile
from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QMessageBox

from src.main.server.controller.login_controller import LoginController



class ClientRegisterWindow:

    def __init__(self, main_window):
        self._load_ui()
        self.main_window = main_window

    def _load_ui(self):
        path = "../../../qt_ui/register.ui"
        file = QFile(path)
        try:
            loader = QUiLoader()
            self.window = loader.load(file)
            self.window.pushButton.clicked.connect(self.show_confirmation_dialog)
            self.window.pushButton_3.clicked.connect(self.login)

        finally:
            file.close()

        if self.window:
            self.window.show()  # 显示独立窗口
        else:
            print("加载 UI 失败，请检查文件路径或内容")

    def login(self):
        from src.main.vision.windows.client_login_window import client_login_window
        client_login_window(self)
        self.close_window()

    def close_window(self):
        """关闭当前窗口"""
        self.window.close()

    def handle_gender_selection(self):
        """按钮组的动态获取"""
        selected_button = self.window.buttonGroup.checkedButton()
        if selected_button:
            self.gender = selected_button.text()
        else:
            self.gender = None

    def register_check(self):
        """注册检查"""
        from src.main.vision.windows.client_login_window import client_login_window
        self.handle_gender_selection()
        username = self.window.lineEdit.text()
        password = self.window.lineEdit_5.text()
        age = self.window.lineEdit_2.text()
        gender = self.gender
        pho_num = self.window.lineEdit_3.text()
        email = self.window.lineEdit_4.text()


        if username and password and gender and age and pho_num:
            LoginController().register(username,
                                       password,
                                       age,
                                       gender,
                                       pho_num,
                                       email
                                       )
            print("注册成功,将自动跳转到登录界面")
            client_login_window(self)
            self.close_window()
        else:
            print("你有未填写的表单信息")

    def show_confirmation_dialog(self):
        # 使用 self.window 作为父级窗口
        reply = QMessageBox.question(
            self.window,
            "确认",
            "是否确定执行此操作？",
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            print("用户选择继续注册")
            self.register_check()
        else:
            print("用户取消注册")

def client_register_window(self):
        self.register_window = ClientRegisterWindow(self)